package com.bhkj.pdjhforotherapp.core.jhaudio;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.bhkj.pdjhforotherapp.R;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.mine.vioceplaylib.sound.SoundManager;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 叫号服务 语音播报
 * 加入前台服务保活机制
 * 如果service被系统杀死的话，需要重新启动该服务
 */
public class JhAudioService extends Service {

    private JhAudioSchduledExcutor jhAudioSchduledExcutor;
    private ScheduledExecutorService scheduledExecutorService;
    public static final int NOTICE_ID = 100;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        keepLiveBeforeNotification();
        if (jhAudioSchduledExcutor == null) {
            jhAudioSchduledExcutor = new JhAudioSchduledExcutor();
        }
        if (scheduledExecutorService == null) {
            scheduledExecutorService = Executors.newScheduledThreadPool(1);
        }
        scheduledExecutorService.scheduleWithFixedDelay(jhAudioSchduledExcutor, 0, 1, TimeUnit.SECONDS);
    }

    /**
     * 保活创建前台notification
     */
    private void keepLiveBeforeNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("叫号保活");
        startForeground(NOTICE_ID, builder.build());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 如果Service被终止
        // 当资源允许情况下，重启service
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //如果service被杀死，就干掉通知
        NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mManager.cancel(NOTICE_ID);

//        jhAudioSchduledExcutor.release();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }

        //重启自己
//        ServiceUtils.startService(JhAudioService.class);
    }
}
